/*
Copyright (c) 2007, Arturo José Guédez Romero

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of Cultusoft nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.cultusoft.groovin.plugins.project;

import com.cultusoft.groovin.plugins.build.ProjectCompleteDependencyFinder;
import com.cultusoft.groovin.plugins.build.ProjectDependencyDownloader
import com.cultusoft.groovin.log.GroovinLogger
import com.cultusoft.groovin.configuration.Configuration
import com.cultusoft.groovin.plugins.changetracker.ProjectChangeTracker
import com.cultusoft.groovin.script.GroovinProperties

class ProjectTester {

    static def logger = new GroovinLogger(ProjectTester.class)
       
    def project

	def neededPackages = [new LibraryProject(group:"junit-addons", id:"junit-addons", version:"1.4"),
                          new LibraryProject(group:"junit",        id:"junit",        version:"4.1")] as List
                          
    def testPatterns = ["**/UTest*.java"] as List

    def test() {
        if (!(ProjectChangeTracker.hasProjectChangedSinceLastBuild(project) ||
             GroovinProperties.isEnabled(GroovinProperties.forceTests))) {
            logger.debug "No changes found for project $project.name, therefore no tests will be run for this project"
            return
		} 
        
        doTest()
       
    }

    private void doTest() {
        downloadNeededPackages()
        runTests()
    }
    
	def downloadNeededPackages() {
        new ProjectDependencyDownloader().downloadLibraries(neededPackages)
	}

	private void runTests() {
        def configuration = new Configuration()
		
		
		File junitReportFolder = new File(configuration.reportFolder, "junitResults")
		
		if (!junitReportFolder.exists()) {
		    junitReportFolder.mkdir()		    
		}

		def ant = new AntBuilder()
		
        logger.log "Setting up tests for project $project.name"
		logger.log("Test report logs are printed in directory " + junitReportFolder.getPath())
		
		ant.mkdir(dir:configuration.reportFolder)
		
		def dependencies = new ProjectCompleteDependencyFinder().findAllDependencies(project.dependencies);

		ant.junit(printsummary:"yes", haltonfailure:"yes", forkmode:"once") {
			classpath { 
					for (project in dependencies) {
                        logger.debug "in classpath of tests: $project.packagingLocation"
						pathelement( location: project.getPackagingLocation())
					}
                    logger.debug "in classpath of tests: $project.packagingLocation"
                    pathelement( location: project.getPackagingLocation())
			}
			
			formatter( type:"plain")
			
			batchtest (fork:"yes", todir:junitReportFolder.getPath()) {
                
                logger.debug "Adding projects to test batch job"
                
                for (pattern in testPatterns) {
                    logger.debug "Test Files matching pattern $pattern will be executed" 
                }
                logger.debug "Tests located under the following folders will be executed"


                for (sourceDirectoryPath in project.sourceDirectoriesPaths) {
                    fileset (dir: sourceDirectoryPath) {
                        logger.debug "source directories used $sourceDirectoryPath"
                            for (pattern in testPatterns) {
                                include (name:pattern)
                            }
                    }
                    logger.debug "Finished adding projects to test batch job. Tests will now start."
                }
			}
		}
		
	}
    

}
